#!/usr/bin/perl
@arr;
@cur;
%letter=("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6, "g"=>7, "h"=>8, "i"=>9, "j"=>0);
foreach $d (@ARGV){
	print $_,"\n";
	&man() if ($_ eq "--help");
	foreach (0..3){
		&sayEr(" Insufficent lenghth of parametr $d") if ( (length $d) != 4 );
		@cur[$_]=substr($d,$_,1);
		&sayEr ("Wrong letter!") if (!(@cur[$_] =~ /^[a-j0-9]+/));
		@cur[$_]=$letter{@cur[$_]} if (exists $letter{@cur[$_]});
	}
	for ($i=0; $i<4; $i+=2){
		for ($a=-1; $a<1; $a++){
			$tmp=(@cur[$i+1]+$a)*10 + @cur[$i];			
			for ($b=-1; $b<1; $b++){
				&sayEr(" Ships too close!") if (($tmp+$b >= 0) && (($tmp+$b)/10 == $tmp/10) && (@arr[$tmp+$b]));
			}		
		}	
	}
	if ( @cur[0] == @cur[2]){
		my $m=&min(@cur[1],@cur[3]);
		&sayEr(" Ship too long!") if ( abs(@cur[1]-@cur[3])>3 );
		for ( $i=0; $i<abs(@cur[1]-@cur[3])+1; $i++ ){
			@arr[10*($m+$i)+@cur[0]]="H";
		}
	}
	elsif ( @cur[1] == @cur[3] ){
		my $m=&min(@cur[0],@cur[2]);
		&sayEr(" Ship too long!") if ( abs(@cur[0]-@cur[2])>3 );
		for($i=0; $i<abs(@cur[0]-@cur[2])+1; $i++){
			@arr[10*@cur[1]+$m+$i]="H";
		}
	}
	else{
	sayEr(" Wrong parametr!")
	}
}

print "  a b c d e f g h i j";
for ($i=0; $i<100; $i++){
	if ( $i%10 == 0 ){
		print "\n", $i/10;
	}
	if (@arr[$i]){
		print " @arr[$i]";
	} 
	else {
		print " .";
	}	
}
print "\n";
printf "\nPlease, read the manual (bash battleship.sh --help) for better using\n";

sub min{
	if ($_[0] > $_[1]){	
		return $_[1];
	}
	return $_[0];
}

sub sayEr{
	print "Error in parametr! @cur ", @_, "\n";
	exit -1;
}

sub man{
print "manual:
Hello user! Thank you for using the program!
This program only print ships according its coordinates and rules of battleship
For printing ships enter its coordinates of begining and finishing in format: 
LetterNumberLetterNumber(a1a1) or NumberNumberNumberNumber(0101) or LetterLetterLetterLetter(abab)
The program follows next rules:
0) Coordinates must be from 0 to 9 or from a to j
1) Length of the ship from 1 to 4
2) The program don't check number of ships! ( in order to reduce time of testing the program by the teacher ;) )
3) Ships must not be closer than 1 cell
4) Ships must not have bends
5) If the coordinates do not satisfy the requirements 0-4, than program won't print the field and will print you about error
6) One cell is \".\" -empty cell or \"H\" -cell with a part of the ship\n\n";
exit 0;
}
